import query from './atom/db/query';
import count from './atom/db/count';
import { IBaseTable } from './atom/db/interfaces';

declare const action_id: string;
declare const session_id: string;
declare const spaceid: string;

interface Message {
	filter: {};
	sort: {};
	page_size: number;
	page_no: number;
}

interface CertifiInfo extends IBaseTable {
	_id:string;
	no:string;
	staff_name:string;
	staff_number:string;
	staff_type:string;
	deptid:string;
	deptname:string;
	companyname:string;
	company_address:string;
	position_name:string;
	start_time:number;
	finish_time:number;
	plan_time:number;
	p_t_job_wages:string;
	memo:string;
}


function format(date: number) {
	if (date === null) {
		return '';
	}
	try {
		const _date = new Date(parseFloat(date + ''));
		if (_date) {
			return _date.getFullYear() + '-' + _format(_date.getMonth() + 1) + '-' + _format(_date.getDate());
		}
		return '';
	} catch (error) {
		return '';
	}
}

function _format(d: number) {
	if (d < 10) {
		return '0' + d;
	} else {
		return d;
	}
}

async function atom(msg: Message) {
	const systemid = '6051';
	const { exec, prepare } = query(action_id, session_id, spaceid, systemid);
	const asc: string[] = [];
	const desc: string[] = [];
	if (msg.sort) {
		const key = Object.keys(msg.sort)[0];
		if (msg.sort[key] === -1) {
			desc.push(key);
		} else {
			asc.push(key);
		}
	}
	// 证照信息
	prepare('outschool_ptjob', [
		'_id','no','staff_name','staff_number','staff_type','deptid','deptname','companyname','company_address','position_name','start_time','finish_time','plan_time','p_t_job_wages','memo'], msg.filter, msg.page_size, msg.page_no, asc, desc);
	const [data] = await exec();

	data.forEach((item:CertifiInfo) => {
		item['start_time_str'] = format(item.start_time);
		item['finish_time_str'] = format(item.finish_time);
		item['plan_time_str'] = format(item.plan_time);
	});

	const c = count(action_id, session_id, spaceid, systemid);
	c.prepare('outschool_ptjob', msg.filter);
	const [t] = await c.exec();

	return { dataArray: data, count: t };
}